<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { familyApi } from '../request'
import type { FamilyInfo } from '../request/api/family'

const userStore = useUserStore()
const error = ref('')
const success = ref('')
const isLoading = ref(false)

// 加入家庭相关
const joinFamilyId = ref('')
const isJoining = ref(false)
const joinError = ref('')
const joinSuccess = ref('')

const familyForm = ref<Omit<FamilyInfo, 'id'>>({
  name: '',
  memberCount: 1,
  hasChildren: false,
  hasElderly: false,
  preferences: {
    spicyLevel: 0,
    allergies: [''],
    dietaryRestrictions: ['']
  }
})

// 获取家庭信息
const fetchFamilyInfo = async () => {
  if (!userStore.user?.familyId) return
  
  try {
    const response = await familyApi.getFamily(userStore.user.familyId)
    familyForm.value = {
      name: response.name,
      memberCount: response.memberCount,
      hasChildren: response.hasChildren,
      hasElderly: response.hasElderly,
      preferences: response.preferences
    }
  } catch (e) {
    console.error('获取家庭信息失败:', e)
  }
}

// 加入现有家庭
const handleJoinFamily = async () => {
  if (!joinFamilyId.value.trim()) {
    joinError.value = '请输入家庭ID'
    return
  }

  try {
    isJoining.value = true
    joinError.value = ''
    joinSuccess.value = ''

    if (!userStore.user?.id) {
      joinError.value = '用户信息不存在'
      return
    }

    await userStore.updateUser(joinFamilyId.value)
    joinSuccess.value = '成功加入家庭'
    
    // 重新获取家庭信息
    await fetchFamilyInfo()
  } catch (error) {
    console.error('加入家庭失败:', error)
    joinError.value = '加入家庭失败，请检查家庭ID是否正确'
  } finally {
    isJoining.value = false
  }
}

// 创建或更新家庭信息
const handleSubmit = async () => {
  try {
    isLoading.value = true
    error.value = ''
    success.value = ''

    let response
    
    // 如果没有家庭ID，先创建家庭
    if (!userStore.user?.familyId) {
      response = await familyApi.createFamily({
        name: familyForm.value.name,
        memberCount: familyForm.value.memberCount,
        hasChildren: familyForm.value.hasChildren,
        hasElderly: familyForm.value.hasElderly,
        preferences: {
          spicyLevel: familyForm.value.preferences.spicyLevel,
          allergies: familyForm.value.preferences.allergies.filter(a => a.trim() !== ''),
          dietaryRestrictions: familyForm.value.preferences.dietaryRestrictions.filter(d => d.trim() !== '')
        }
      })

      // 更新用户的家庭ID
      if (response) {
        await userStore.updateUser(response.id)
      }
    } else {
      // 更新家庭信息
      response = await familyApi.updateFamily(userStore.user.familyId, {
        name: familyForm.value.name,
        memberCount: familyForm.value.memberCount,
        hasChildren: familyForm.value.hasChildren,
        hasElderly: familyForm.value.hasElderly,
        preferences: {
          spicyLevel: familyForm.value.preferences.spicyLevel,
          allergies: familyForm.value.preferences.allergies.filter(a => a.trim() !== ''),
          dietaryRestrictions: familyForm.value.preferences.dietaryRestrictions.filter(d => d.trim() !== '')
        }
      })
    }

    success.value = '家庭信息保存成功'
  } catch (e) {
    error.value = '保存失败，请稍后重试'
    console.error('更新家庭信息失败:', e)
  } finally {
    isLoading.value = false
  }
}

// 添加过敏食材
const addAllergy = () => {
  familyForm.value.preferences.allergies.push('')
}

// 移除过敏食材
const removeAllergy = (index: number) => {
  familyForm.value.preferences.allergies.splice(index, 1)
}

// 添加饮食限制
const addDietaryRestriction = () => {
  familyForm.value.preferences.dietaryRestrictions.push('')
}

// 移除饮食限制
const removeDietaryRestriction = (index: number) => {
  familyForm.value.preferences.dietaryRestrictions.splice(index, 1)
}

onMounted(fetchFamilyInfo)
</script>

<template>
  <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- 加入家庭 -->
    <div v-if="!userStore.user?.familyId" class="card mb-8">
      <div class="p-6">
        <h2 class="text-2xl font-bold text-gray-900 mb-4">加入现有家庭</h2>
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">家庭ID</label>
            <div class="flex gap-4">
              <input
                v-model="joinFamilyId"
                type="text"
                class="input flex-1"
                placeholder="请输入家庭ID"
              />
              <button
                @click="handleJoinFamily"
                class="btn btn-primary"
                :disabled="isJoining"
              >
                {{ isJoining ? '加入中...' : '加入家庭' }}
              </button>
            </div>
          </div>

          <div v-if="joinError" class="text-red-500 text-sm">
            {{ joinError }}
          </div>

          <div v-if="joinSuccess" class="text-green-500 text-sm">
            {{ joinSuccess }}
          </div>

          <div class="text-sm text-gray-500">
            <p>如果您已经有家庭成员创建了家庭，请输入他们的家庭ID进行加入。</p>
            <p>或者您可以创建一个新的家庭。</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建/编辑家庭信息 -->
    <div class="card">
      <div class="p-6">
        <h1 class="text-3xl font-bold text-gray-900 mb-8">
          {{ userStore.user?.familyId ? '家庭信息设置' : '创建新家庭' }}
        </h1>
        
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 基本信息 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">家庭名称</label>
            <input
              v-model="familyForm.name"
              type="text"
              required
              class="input"
              placeholder="例如：张家"
            />
          </div>

          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">家庭成员数量</label>
              <input
                v-model.number="familyForm.memberCount"
                type="number"
                min="1"
                required
                class="input"
              />
            </div>
            
            <div class="flex items-center space-x-2">
              <input
                v-model="familyForm.hasChildren"
                type="checkbox"
                id="has-children"
                class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
              />
              <label for="has-children" class="text-sm font-medium text-gray-700">
                有儿童
              </label>
            </div>
            
            <div class="flex items-center space-x-2">
              <input
                v-model="familyForm.hasElderly"
                type="checkbox"
                id="has-elderly"
                class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
              />
              <label for="has-elderly" class="text-sm font-medium text-gray-700">
                有老人
              </label>
            </div>
          </div>

          <!-- 辣度偏好 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">可接受的最高辣度</label>
            <input
              v-model.number="familyForm.preferences.spicyLevel"
              type="range"
              min="0"
              max="5"
              class="w-full"
            />
            <div class="flex justify-between text-xs text-gray-500">
              <span>不辣</span>
              <span>微辣</span>
              <span>中辣</span>
              <span>特辣</span>
              <span>超辣</span>
              <span>地狱辣</span>
            </div>
          </div>

          <!-- 过敏食材 -->
          <div>
            <div class="flex justify-between items-center mb-2">
              <label class="block text-sm font-medium text-gray-700">过敏食材</label>
              <button
                type="button"
                @click="addAllergy"
                class="text-sm text-primary-600 hover:text-primary-500"
              >
                添加食材
              </button>
            </div>
            <div class="space-y-2">
              <div
                v-for="(allergy, index) in familyForm.preferences.allergies"
                :key="index"
                class="flex gap-2"
              >
                <input
                  v-model="familyForm.preferences.allergies[index]"
                  type="text"
                  class="input"
                  placeholder="例如：花生"
                />
                <button
                  type="button"
                  @click="removeAllergy(index)"
                  class="text-red-500 hover:text-red-600"
                >
                  删除
                </button>
              </div>
            </div>
          </div>

          <!-- 饮食限制 -->
          <div>
            <div class="flex justify-between items-center mb-2">
              <label class="block text-sm font-medium text-gray-700">饮食限制</label>
              <button
                type="button"
                @click="addDietaryRestriction"
                class="text-sm text-primary-600 hover:text-primary-500"
              >
                添加限制
              </button>
            </div>
            <div class="space-y-2">
              <div
                v-for="(restriction, index) in familyForm.preferences.dietaryRestrictions"
                :key="index"
                class="flex gap-2"
              >
                <input
                  v-model="familyForm.preferences.dietaryRestrictions[index]"
                  type="text"
                  class="input"
                  placeholder="例如：素食"
                />
                <button
                  type="button"
                  @click="removeDietaryRestriction(index)"
                  class="text-red-500 hover:text-red-600"
                >
                  删除
                </button>
              </div>
            </div>
          </div>

          <div v-if="error" class="text-red-500 text-sm text-center">
            {{ error }}
          </div>

          <div v-if="success" class="text-green-500 text-sm text-center">
            {{ success }}
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end">
            <button
              type="submit"
              class="btn btn-primary"
              :disabled="isLoading"
            >
              {{ isLoading ? '保存中...' : '保存设置' }}
            </button>
          </div>
        </form>

        <!-- 显示当前家庭ID -->
        <div v-if="userStore.user?.familyId" class="mt-8 p-4 bg-gray-50 rounded-lg">
          <p class="text-sm text-gray-600">
            当前家庭ID：<span class="font-medium text-gray-900">{{ userStore.user.familyId }}</span>
          </p>
          <p class="text-xs text-gray-500 mt-1">
            其他家庭成员可以使用此ID加入您的家庭
          </p>
        </div>
      </div>
    </div>
  </div>
</template>